package com.hschinese.pronunciation.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.bean.AnswerRecordBean;
import com.hschinese.pronunciation.bean.LearnRecordBean;
import com.hschinese.pronunciation.db.DBHelper;
import com.hschinese.pronunciation.utils.Constant;
import com.hschinese.pronunciation.utils.Logger;
import com.hschinese.pronunciation.utils.MD5Utils;
import com.hschinese.pronunciation.utils.SharedPreferenceUtils;
import com.hschinese.pronunciation.utils.Utils;
import com.hschinese.pronunciation.utils.WebRequestUtil;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class EntryActivity extends BaseActivity implements View.OnClickListener {
    private ViewPager mViewPage;
    private ImageView mPage1Tag, mPage2Tag;
    private ImageView mEntryAbout, mEntryResult;
    private ImageView mTitle1View, mTitle2View;

    private List<View> mViewsList = null;
    private EntryViewPageAdapter mAdapter;
    private SharedPreferenceUtils mSharedPrefUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entry);
        mSharedPrefUtil = SharedPreferenceUtils.getInstance(EntryActivity.this);
        initViews();
        initAdapter();
        refreshCurIcon(0);
        updateRecord();
        updateLearnRecord();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initViews() {
        mViewPage = (ViewPager) findViewById(R.id.entry_view_pager);
        mTitle1View = (ImageView)findViewById(R.id.entry_title1);
        mTitle2View = (ImageView)findViewById(R.id.entry_title2);
        mPage1Tag = (ImageView)findViewById(R.id.entry_page1_icon);
        mPage2Tag = (ImageView)findViewById(R.id.entry_page2_icon);
        mEntryAbout = (ImageView)findViewById(R.id.entry_about);
        mEntryResult = (ImageView)findViewById(R.id.entry_test_result_r);

        mPage1Tag.setOnClickListener(this);
        mPage2Tag.setOnClickListener(this);

        mEntryAbout.setOnClickListener(this);
        mEntryResult.setOnClickListener(this);

        setTitleImage();
    }

    private void setTitleImage() {
        String la = Utils.getLanguage(EntryActivity.this);
        if (Constant.LANGUAGE_JAPANESE.equals(la)) {
            mTitle1View.setImageResource(R.drawable.ic_about_t_ja);
        } else if ("zh-hans".equals(la)) {
            mTitle1View.setImageResource(R.drawable.ic_about_t);
        } else if (Constant.LANGUAGE_KOREAN.equals(la)) {
            mTitle1View.setImageResource(R.drawable.ic_about_t_ko);
        } else if (Constant.LANGUAGE_ENGLISH.equals(la)) {
            mTitle1View.setImageResource(R.drawable.ic_about_t_en);
        }
    }

    private void initAdapter() {
        mViewsList = new ArrayList<View>();
        LayoutInflater mLi = LayoutInflater.from(this);
        View page1 = mLi.inflate(R.layout.entry_page1, null);
        View page2 = mLi.inflate(R.layout.entry_page2, null);
        View entry1 = page1.findViewById(R.id.entry_single_phone);
        View entry2 = page1.findViewById(R.id.entry_double_phone);
        View entry3 = page1.findViewById(R.id.entry_single_phone_practise);
        View entry4 = page1.findViewById(R.id.entry_double_phone_practise);
        View tv_add_two = page1.findViewById(R.id.tv_add_two);
        View tv_add_one = page1.findViewById(R.id.tv_add_one);
        entry1.setOnClickListener(this);
        entry2.setOnClickListener(this);
        entry3.setOnClickListener(this);
        entry4.setOnClickListener(this);
        tv_add_two.setOnClickListener(this);
        tv_add_one.setOnClickListener(this);

        View entry21 = page2.findViewById(R.id.entry_consonants);
        View entry22 = page2.findViewById(R.id.entry_pronunciation_practise);
        View entry23 = page2.findViewById(R.id.entry_vowels);
        View entry24 = page2.findViewById(R.id.entry_ba);
        entry21.setOnClickListener(this);
        entry22.setOnClickListener(this);
        entry23.setOnClickListener(this);
        entry24.setOnClickListener(this);

        setTextTypeface(page1, page2);
        mViewsList.add(page1);
        mViewsList.add(page2);
        mAdapter = new EntryViewPageAdapter();
        mViewPage.setAdapter(mAdapter);
        mViewPage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
            }

            @Override
            public void onPageSelected(int i) {
                refreshCurIcon(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });
    }

    private void setTextTypeface(View page1, View page2) {
        TextView txt1 = (TextView)page1.findViewById(R.id.entry_icon_1);
        TextView txt2 = (TextView)page1.findViewById(R.id.entry_icon_2);
        TextView txt3 = (TextView)page2.findViewById(R.id.entry_icon_3);
        Typeface type = Typeface.createFromAsset(getAssets(), "fonts/hanyupinyin.ttf");
        txt1.setTypeface(type);
        txt2.setTypeface(type);
        txt3.setTypeface(type);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        int choosedLesson = 0;
        if (id == R.id.entry_single_phone) {
            choosedLesson = 0;
            startActivity(choosedLesson);
        } if (id == R.id.tv_add_two) {
            choosedLesson = 9;
            startActivity(choosedLesson);
        } if (id == R.id.tv_add_one) {
            choosedLesson = 8;
            startActivity(choosedLesson);
        } else if (id == R.id.entry_single_phone_practise) {
            choosedLesson = 1;
            startActivity(choosedLesson);
        }else if (id == R.id.entry_double_phone) {
            choosedLesson = 2;
            startActivity(choosedLesson);
        } else if (id == R.id.entry_double_phone_practise) {
            choosedLesson = 3;
            startActivity(choosedLesson);
        } else if (id == R.id.entry_vowels) {
            choosedLesson = 4;
            Intent it = new Intent(EntryActivity.this, WordListActivity.class);
            it.putExtra("lessonType", choosedLesson);
            startActivity(it);
        } else if (id == R.id.entry_consonants) {
            choosedLesson = 5;
            Intent it = new Intent(EntryActivity.this, WordListActivity.class);
            it.putExtra("lessonType", choosedLesson);
            startActivity(it);
        } else if (id == R.id.entry_ba) {
            choosedLesson = 6;
            startActivity(choosedLesson);
        }else if (id == R.id.entry_pronunciation_practise) {
            choosedLesson = 7;
            startActivity(choosedLesson);
        } else if (id == R.id.entry_about) {
            Intent it = new Intent(EntryActivity.this, MoreActivity.class);
            startActivity(it);
        } else if (id == R.id.entry_test_result_r) {
            Intent intent = new Intent(EntryActivity.this, ToneCheckReportActivity.class);
            intent.putExtra("lessonType","lessonType");
            startActivity(intent);
        }
    }

    private void refreshCurIcon(int flag) {
        if (flag == 0) {
//            mTitle2View.setImageResource(R.drawable.ic_entry_shengdiao);
            mPage1Tag.setImageResource(R.drawable.ic_page_focus);
            mPage2Tag.setImageResource(R.drawable.ic_page_unfocus);
        } else {
            mPage2Tag.setImageResource(R.drawable.ic_page_focus);
            mPage1Tag.setImageResource(R.drawable.ic_page_unfocus);
//            mTitle2View.setImageResource(R.drawable.ic_hanyupinyinfangan);
        }
        setTitle2Image(flag);
    }

    private void setTitle2Image(int flag) {
        String la = Utils.getLanguage(EntryActivity.this);
        Logger.e("xionghy - EntryActivity la: " + la);
        if (flag == 0) {
            if (Constant.LANGUAGE_JAPANESE.equals(la)) {
                mTitle2View.setImageResource(R.drawable.ic_entry_shengdiao_ja);
            } else if ("zh-hans".equals(la)) {
                mTitle2View.setImageResource(R.drawable.ic_entry_shengdiao);
            } else if (Constant.LANGUAGE_KOREAN.equals(la)) {
                mTitle2View.setImageResource(R.drawable.ic_entry_shengdiao_ko);
            } else if (Constant.LANGUAGE_ENGLISH.equals(la)) {
                mTitle2View.setImageResource(R.drawable.ic_entry_shengdiao_en);
            }
        } else {
            if (Constant.LANGUAGE_JAPANESE.equals(la)) {
                mTitle2View.setImageResource(R.drawable.ic_hanyupinyinfangan_ja);
            } else if ("zh-hans".equals(la)) {
                mTitle2View.setImageResource(R.drawable.ic_hanyupinyinfangan);
            } else if (Constant.LANGUAGE_KOREAN.equals(la)) {
                mTitle2View.setImageResource(R.drawable.ic_hanyupinyinfangan_ko);
            } else if (Constant.LANGUAGE_ENGLISH.equals(la)) {
                mTitle2View.setImageResource(R.drawable.ic_hanyupinyinfangan_en);
            }
        }
    }

    private void startActivity(int i) {


        Intent it = new Intent(EntryActivity.this, StudyActivity.class);
        it.putExtra("lesson", i);
        startActivity(it);
    }



    class EntryViewPageAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mViewsList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view == o;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewsList.get(position));
            return mViewsList.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewsList.get(position));
        }
    }

    private void updateRecord() {
        List<AnswerRecordBean> beanList = new ArrayList<AnswerRecordBean>();
        Cursor cursor = DBHelper.getInstance(getApplicationContext()).query(DBHelper.ANSWER_RECORD, null, null);
        while(cursor.moveToNext()) {
            AnswerRecordBean bean = new AnswerRecordBean();
            bean.setChinese(cursor.getString(cursor.getColumnIndex("chinese")));
            bean.setRightTimes(cursor.getInt(cursor.getColumnIndex("rightTimes")));
            bean.setResult(cursor.getString(cursor.getColumnIndex("result")));
            bean.setTimestamp(cursor.getString(cursor.getColumnIndex("timestamp")));
            bean.setUserAnswer(cursor.getString(cursor.getColumnIndex("userAnswer")));
            bean.setWrongTimes(cursor.getInt(cursor.getColumnIndex("wrongTimes")));
            bean.setRecordID(cursor.getString(cursor.getColumnIndex("recordID")));
            beanList.add(bean);
            Logger.e("xionghy --- " + bean.toString());
        }
        if (beanList.size() > 0) {
            uploadRecord(beanList);
        }
        if (cursor != null) {
            cursor.close();
        }
    }

    /**
     * 开启线程过来上传数据
     * http://api.hschinese.com/talk/practice/records
     */
    private void uploadRecord(List<AnswerRecordBean> list) {
        String url = "http://api.hschinese.com/talk/practice/records";
        String record = "";
        for (int i=0; i<list.size(); i++) {
            AnswerRecordBean b = list.get(i);
            if (i != 0) {
                record += ",";
            }
            record += b.getRecordID() + "|" + b.getChinese() + "|" + b.getRightTimes() + "|"
                    + b.getWrongTimes() + "|" + b.getResult() + "|"+b.getTimestamp();
        }
        SharedPreferenceUtils mSharedPrefUtil = SharedPreferenceUtils.getInstance(EntryActivity.this);
        String uid = mSharedPrefUtil.getuserInfo().getUid();
        String email = mSharedPrefUtil.getuserInfo().getEmail();
        String apkey =  null;
        try {
            apkey = MD5Utils.getMD5(email + Constant.PRODUCT_ID + "hansheng");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("apkey", apkey);
        params.put("uID", uid);
        params.put("pointID", "");
        params.put("language", Utils.getLanguage(EntryActivity.this));
        params.put("records", record);
        params.put("productVersion", Utils.getVersionCode(EntryActivity.this) + "");
        params.put("productID", Constant.PRODUCT_ID);
        WebRequestUtil.getInstance(EntryActivity.this).postRequestString(url, params, new Response.Listener<String>(){
            @Override
            public void onResponse(String json) {
                Logger.e("xionghy - upload result: " + json);
                DBHelper.getInstance(EntryActivity.this).dropAnswerTable();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
    }

    private void updateLearnRecord() {
        List<LearnRecordBean> beanList = new ArrayList<LearnRecordBean>();
        Cursor cursor = DBHelper.getInstance(getApplicationContext()).query(DBHelper.LEARN_RECORD, null, null);
        while(cursor.moveToNext()) {
            LearnRecordBean bean = new LearnRecordBean();
            bean.setRecordID(cursor.getString(cursor.getColumnIndex("recordID")));
            bean.setChinese(cursor.getString(cursor.getColumnIndex("chinese")));
            bean.setLearnedTimes(cursor.getInt(cursor.getColumnIndex("learnedTimes")));
            bean.setLearnType(cursor.getString(cursor.getColumnIndex("learnType")));
            bean.setTimestamp(cursor.getString(cursor.getColumnIndex("timestamp")));
            beanList.add(bean);
            Logger.e("xionghy --- " + bean.toString());
        }
        if (beanList.size() > 0) {
            uploadLearnRecord(beanList);
        }
        if (cursor != null) {
            cursor.close();
        }
    }

    private void uploadLearnRecord(List<LearnRecordBean> list) {
        String url = "http://api.hschinese.com/talk/learn/records";
        String record = "";
        for (int i=0; i<list.size(); i++) {
            LearnRecordBean b = list.get(i);
            if (i != 0) {
                record += ",";
            }
            record += b.getRecordID() + "|" + b.getChinese() + "|" + b.getLearnedTimes() + "|"
                    + b.getLearnType() + "|"+b.getTimestamp();
        }
        SharedPreferenceUtils mSharedPrefUtil = SharedPreferenceUtils.getInstance(EntryActivity.this);
        String uid = mSharedPrefUtil.getuserInfo().getUid();
        String email = mSharedPrefUtil.getuserInfo().getEmail();
        String apkey =  null;
        try {
            apkey = MD5Utils.getMD5(uid + Constant.PRODUCT_ID + "hansheng");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("apkey", apkey);
        params.put("uID", uid);
        params.put("language", Utils.getLanguage(EntryActivity.this));
        params.put("records", record);
        params.put("productVersion", Utils.getVersionCode(EntryActivity.this) + "");
        params.put("productID", Constant.PRODUCT_ID);
        WebRequestUtil.getInstance(EntryActivity.this).postRequestString(url, params, new Response.Listener<String>(){
            @Override
            public void onResponse(String json) {
                Logger.e("xionghy - upload learn record result: " + json);
                DBHelper.getInstance(EntryActivity.this).drapLearnTable();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
    }
}
